from random import shuffle, randint
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from forms import WordForm
from models import Word, QuizItem

class AddWord(webapp.RequestHandler):
    def get(self):
        context = {
            "form": WordForm(),
            "action": "/add-word"
        }
        self.response.out.write(template.render("templates/editor.html", context))

    def post(self):
        data = WordForm(data=self.request.POST)
        if data.is_valid():
            data.save()
            self.redirect("/list-words")
        else:
            context = {
                "form": data,
                "action": "/add-word"
            }
            self.response.out.write(template.render("templates/editor.html", context))

class ListWords(webapp.RequestHandler):
    def get(self):
        context = {
            "words": Word.all().filter("owner =", users.get_current_user()).fetch(1000),
            "log_out": users.create_logout_url("/")
        }
        self.response.out.write(template.render("templates/list.html", context))

class DeleteWord(webapp.RequestHandler):
    def post(self):
        Word.get(self.request.POST.get("key")).delete()
        self.redirect("/list-words")

class EditWord(webapp.RequestHandler):
    def get(self, key):
        word = Word.get(key)
        context = {
            "form": WordForm(instance=word),
            "action": "/edit-word",
            "key": word.key()
        }
        self.response.out.write(template.render("templates/editor.html", context))

    def post(self):
        word = Word.get(self.request.POST.get("key"))
        data = WordForm(data=self.request.POST, instance=word)
        if data.is_valid():
            data.save()
            self.redirect("/list-words")
        else:
            context = {
                "form": data,
                "action": "/edit-word",
                "key": word.key()
            }
            self.response.out.write(template.render("templates/editor.html", context))

class AddMultipleWords(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render("templates/batch-editor.html", {}))

    def post(self):
        words = self.request.POST.get("words")
        if words:
            spelling = None
            for line in words.splitlines():
                if not spelling:
                    spelling = line.strip()
                else:
                    Word(
                        spelling=spelling,
                        translations=[x.strip() for x in line.split(",")]).save()
                    spelling = None
        self.redirect("/list-words")

class Quiz(webapp.RequestHandler):
    def get(self):
        words = Word.all().filter("owner =", users.get_current_user()).filter("score <=", 5).order("score").fetch(15)
        group_len = 5
        groups_count = len(words)/group_len + (0 if len(words)%group_len == 0 else 1)
        items = [QuizItem(spelling=word.spelling, spelling_key=word.key()) for word in words]
        result = []
        for i in range(0, groups_count):
            group = items[i*group_len: min((i + 1)*group_len, len(items))]
            shuffle(group)
            for j in range(0, len(group)):
                item = group[j]
                word = words[i*group_len + j]
                item.translation = word.translations[randint(0, len(word.translations) - 1)]
                item.translation_key = word.key()
            result += group
        context = {
            "items": result,
            "group_len": group_len
        }
        self.response.out.write(template.render("templates/quiz.html", context))

    def post(self):
        keys = [x.strip() for x in self.request.POST.get("keys").split(";") if x]
        for key in keys:
            word = Word.get(key)
            word.score += int(self.request.POST.get(key))
            word.save()